import Taro from '@tarojs/taro';
import { extend, isObject } from '.';
import { primaryColor } from './config';

const success = (options, noClog) => {
  const title = typeof options == 'string' ? options : options.title;
  var def = {
    icon: 'none',
    duration: 1200,
    mask: true,
    title
  };
  if (isObject(options)) {
    Object.assign(def, options);
  }
  Taro.showToast(def);
  if (!noClog) {
    return Promise.sleep(1500);
  }
};

const confirm = (options, title = '') => {
  const content = typeof options == 'string' ? options : options.content;

  var def = {
    cancelText: '取消',
    confirmText: '确认',
    confirmColor: primaryColor.value,
    cancelColor: '#999999',
    showCancel: true,
    content: content,
    title
  };
  if (isObject(options)) {
    Object.assign(def, options);
  }
  return new Promise((resolve, reject) => {
    Taro.showModal({
      ...def,
      fail(res) {
        reject(res);
      },
      success({ confirm, cancel }) {
        if (confirm) {
          resolve();
        } else {
          reject('取消');
        }
      }
    });
  });
};

const alert = (content, title = '') => {
  return confirm({
    content,
    title,
    showCancel: false
  });
};

const loading = (title = '', mask = true) => {
  Taro.showLoading({
    title,
    mask
  });
  return () => Taro.hideLoading();
};

export default {
  success,
  confirm,
  alert,
  loading: extend(loading, {
    async lock(callback) {
      const close = loading();
      try {
        await callback();
      } finally {
        close();
      }
    },
    show() {
      return loading;
    },
    close() {
      Taro.hideLoading();
    }
  }),
  error: message => {
    return success(
      {
        // icon: 'error',
        title: message,
        mask: false
      },
      false
    );
  }
};
